<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>串口配置 - DTU管理系统</title>
    <script src="js/toast.js"></script>
    <link rel="stylesheet" href="css/common.css">
    <style>
        
        .test-result {
            margin-top: 1rem;
            padding: 1rem;
            border-radius: 4px;
            font-family: monospace;
        }
        
        .test-result.success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .test-result.error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>串口配置</h1>
        <div class="breadcrumb">DTU管理系统 > 串口配置</div>
    </div>

    <div class="container">
        <!-- Tab导航 -->
        <div class="nav-tabs">
            <a href="index.html" class="nav-tab">首页</a>
            <a href="network.html" class="nav-tab">网络配置</a>
            <a href="serial.html" class="nav-tab active">串口配置</a>
            <a href="collect.html" class="nav-tab">数据采集</a>
            <a href="push.html" class="nav-tab">数据推送</a>
            <a href="at-command.html" class="nav-tab">AT命令</a>
            <a href="system.html" class="nav-tab">系统设置</a>
        </div>

        <!-- RS485配置 -->
        <div class="card">
            <div class="card-header">RS485串口配置</div>
            <div class="card-body">
                <form id="rs485-form">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="rs485-device">设备路径</label>
                            <input type="text" id="rs485-device" value="/dev/ttyUSB0" placeholder="/dev/ttyUSB0">
                        </div>
                        <div class="form-group">
                            <label for="rs485-baudrate">波特率</label>
                            <select id="rs485-baudrate">
                                <option value="1200">1200</option>
                                <option value="2400">2400</option>
                                <option value="4800">4800</option>
                                <option value="9600" selected>9600</option>
                                <option value="19200">19200</option>
                                <option value="38400">38400</option>
                                <option value="57600">57600</option>
                                <option value="115200">115200</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label for="rs485-databits">数据位</label>
                            <select id="rs485-databits">
                                <option value="7">7</option>
                                <option value="8" selected>8</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="rs485-stopbits">停止位</label>
                            <select id="rs485-stopbits">
                                <option value="1" selected>1</option>
                                <option value="2">2</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="rs485-parity">校验位</label>
                            <select id="rs485-parity">
                                <option value="none" selected>无</option>
                                <option value="odd">奇校验</option>
                                <option value="even">偶校验</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-actions">
                        <button type="button" class="btn btn-primary" onclick="saveRS485Config()">保存RS485配置</button>
                        <button type="button" class="btn btn-secondary" onclick="testRS485()">测试RS485</button>
                    </div>
                    
                    <div id="rs485-test-result" class="test-result" style="display: none;"></div>
                </form>
            </div>
        </div>

        <!-- RS232配置 -->
        <div class="card">
            <div class="card-header">RS232串口配置</div>
            <div class="card-body">
                <form id="rs232-form">
                    <div class="form-row">
                        <div class="form-group">
                            <label for="rs232-device">设备路径</label>
                            <input type="text" id="rs232-device" value="/dev/ttyUSB1" placeholder="/dev/ttyUSB1">
                        </div>
                        <div class="form-group">
                            <label for="rs232-baudrate">波特率</label>
                            <select id="rs232-baudrate">
                                <option value="1200">1200</option>
                                <option value="2400">2400</option>
                                <option value="4800">4800</option>
                                <option value="9600" selected>9600</option>
                                <option value="19200">19200</option>
                                <option value="38400">38400</option>
                                <option value="57600">57600</option>
                                <option value="115200">115200</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-row">
                        <div class="form-group">
                            <label for="rs232-databits">数据位</label>
                            <select id="rs232-databits">
                                <option value="7">7</option>
                                <option value="8" selected>8</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="rs232-stopbits">停止位</label>
                            <select id="rs232-stopbits">
                                <option value="1" selected>1</option>
                                <option value="2">2</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="rs232-parity">校验位</label>
                            <select id="rs232-parity">
                                <option value="none" selected>无</option>
                                <option value="odd">奇校验</option>
                                <option value="even">偶校验</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-actions">
                        <button type="button" class="btn btn-primary" onclick="saveRS232Config()">保存RS232配置</button>
                        <button type="button" class="btn btn-secondary" onclick="testRS232()">测试RS232</button>
                    </div>
                    
                    <div id="rs232-test-result" class="test-result" style="display: none;"></div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            loadSerialConfig();
        });

        // 加载串口配置
        async function loadSerialConfig() {
            try {
                const response = await fetch('/api/serial');
                const config = await response.json();
                console.log('串口配置:', config);

                if (config.rs485) {
                    const rs485 = config.rs485;
                    document.getElementById('rs485-device').value = rs485.device || '/dev/ttyUSB0';
                    document.getElementById('rs485-baudrate').value = rs485.baudrate || 9600;
                    document.getElementById('rs485-databits').value = rs485.databits || 8;
                    document.getElementById('rs485-stopbits').value = rs485.stopbits || 1;

                    // 处理parity字段 - 后端返回字符，前端需要字符串
                    let parity = 'none';
                    if (rs485.parity === 'N' || rs485.parity === 'n') {
                        parity = 'none';
                    } else if (rs485.parity === 'O' || rs485.parity === 'o') {
                        parity = 'odd';
                    } else if (rs485.parity === 'E' || rs485.parity === 'e') {
                        parity = 'even';
                    }
                    document.getElementById('rs485-parity').value = parity;
                }

                if (config.rs232) {
                    const rs232 = config.rs232;
                    document.getElementById('rs232-device').value = rs232.device || '/dev/ttyUSB1';
                    document.getElementById('rs232-baudrate').value = rs232.baudrate || 9600;
                    document.getElementById('rs232-databits').value = rs232.databits || 8;
                    document.getElementById('rs232-stopbits').value = rs232.stopbits || 1;

                    // 处理parity字段 - 后端返回字符，前端需要字符串
                    let parity = 'none';
                    if (rs232.parity === 'N' || rs232.parity === 'n') {
                        parity = 'none';
                    } else if (rs232.parity === 'O' || rs232.parity === 'o') {
                        parity = 'odd';
                    } else if (rs232.parity === 'E' || rs232.parity === 'e') {
                        parity = 'even';
                    }
                    document.getElementById('rs232-parity').value = parity;
                }

                showMessage('串口配置加载成功', 'success');
            } catch (error) {
                console.error('加载串口配置失败:', error);
                showMessage('加载串口配置失败: ' + error.message, 'error');
            }
        }

        // 保存RS485配置
        async function saveRS485Config() {
            try {
                // 获取表单值
                const device = document.getElementById('rs485-device').value;
                const baudrate = parseInt(document.getElementById('rs485-baudrate').value);
                const databits = parseInt(document.getElementById('rs485-databits').value);
                const stopbits = parseInt(document.getElementById('rs485-stopbits').value);
                const paritySelect = document.getElementById('rs485-parity').value;

                // 将parity选择值转换为单个字符
                let parity = 'N';
                if (paritySelect === 'odd') {
                    parity = 'O';
                } else if (paritySelect === 'even') {
                    parity = 'E';
                }

                // 构建扁平的JSON结构，与后端期望的格式匹配
                const config = {
                    rs485_device: device,
                    rs485_baudrate: baudrate,
                    rs485_databits: databits,
                    rs485_stopbits: stopbits,
                    rs485_parity: parity,
                    rs485_timeout: 1000  // 默认超时时间
                };

                console.log('保存RS485配置:', config);
                const response = await fetch('/api/serial', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(config)
                });

                const result = await response.json();
                if (result.result === 'success') {
                    showMessage('RS485配置保存成功', 'success');
                } else {
                    showMessage('RS485配置保存失败: ' + (result.message || '未知错误'), 'error');
                }
            } catch (error) {
                console.error('保存RS485配置失败:', error);
                showMessage('RS485配置保存失败: ' + error.message, 'error');
            }
        }

        // 保存RS232配置
        async function saveRS232Config() {
            try {
                // 获取表单值
                const device = document.getElementById('rs232-device').value;
                const baudrate = parseInt(document.getElementById('rs232-baudrate').value);
                const databits = parseInt(document.getElementById('rs232-databits').value);
                const stopbits = parseInt(document.getElementById('rs232-stopbits').value);
                const paritySelect = document.getElementById('rs232-parity').value;

                // 将parity选择值转换为单个字符
                let parity = 'N';
                if (paritySelect === 'odd') {
                    parity = 'O';
                } else if (paritySelect === 'even') {
                    parity = 'E';
                }

                // 构建扁平的JSON结构，与后端期望的格式匹配
                const config = {
                    rs232_device: device,
                    rs232_baudrate: baudrate,
                    rs232_databits: databits,
                    rs232_stopbits: stopbits,
                    rs232_parity: parity,
                    rs232_timeout: 1000  // 默认超时时间
                };

                console.log('保存RS232配置:', config);
                const response = await fetch('/api/serial', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(config)
                });

                const result = await response.json();
                if (result.result === 'success') {
                    showMessage('RS232配置保存成功', 'success');
                } else {
                    showMessage('RS232配置保存失败: ' + (result.message || '未知错误'), 'error');
                }
            } catch (error) {
                console.error('保存RS232配置失败:', error);
                showMessage('RS232配置保存失败: ' + error.message, 'error');
            }
        }

        // 测试RS485
        async function testRS485() {
            const resultDiv = document.getElementById('rs485-test-result');
            resultDiv.style.display = 'block';
            resultDiv.className = 'test-result';
            resultDiv.textContent = '正在测试RS485连接...';

            try {
                const config = {
                    serial_type: 'RS485',
                    device: document.getElementById('rs485-device').value,
                    baudrate: parseInt(document.getElementById('rs485-baudrate').value),
                    databits: parseInt(document.getElementById('rs485-databits').value),
                    stopbits: parseInt(document.getElementById('rs485-stopbits').value),
                    parity: document.getElementById('rs485-parity').value
                };

                const response = await fetch('/api/serial/test', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(config)
                });

                const result = await response.json();
                if (result.success) {
                    resultDiv.className = 'test-result success';
                    resultDiv.textContent = 'RS485测试成功: ' + result.message;
                } else {
                    resultDiv.className = 'test-result error';
                    resultDiv.textContent = 'RS485测试失败: ' + (result.error || '未知错误');
                }
            } catch (error) {
                resultDiv.className = 'test-result error';
                resultDiv.textContent = 'RS485测试失败: ' + error.message;
            }
        }

        // 测试RS232
        async function testRS232() {
            const resultDiv = document.getElementById('rs232-test-result');
            resultDiv.style.display = 'block';
            resultDiv.className = 'test-result';
            resultDiv.textContent = '正在测试RS232连接...';

            try {
                const config = {
                    serial_type: 'RS232',
                    device: document.getElementById('rs232-device').value,
                    baudrate: parseInt(document.getElementById('rs232-baudrate').value),
                    databits: parseInt(document.getElementById('rs232-databits').value),
                    stopbits: parseInt(document.getElementById('rs232-stopbits').value),
                    parity: document.getElementById('rs232-parity').value
                };

                const response = await fetch('/api/serial/test', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(config)
                });

                const result = await response.json();
                if (result.success) {
                    resultDiv.className = 'test-result success';
                    resultDiv.textContent = 'RS232测试成功: ' + result.message;
                } else {
                    resultDiv.className = 'test-result error';
                    resultDiv.textContent = 'RS232测试失败: ' + (result.error || '未知错误');
                }
            } catch (error) {
                resultDiv.className = 'test-result error';
                resultDiv.textContent = 'RS232测试失败: ' + error.message;
            }
        }
    </script>
</body>
</html>
